package com.gingko.duominuo.ui.adapter


import android.annotation.SuppressLint
import android.content.Context
import android.telecom.Call
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.gingko.duominuo.data.model.TaskVo
import com.gingko.duominuo.databinding.ItemTaskBinding
import com.gingko.duominuo.utils.NameMappingUtils
import com.gingko.duominuo.utils.millis2String
import com.gingko.duominuo.utils.singleClick
import com.gingko.duominuo.utils.string2Millis

class TaskAdapter(val context: Context, val data: List<TaskVo>) :
    RecyclerView.Adapter<TaskAdapter.TaskHolder>() {
    var callback: Callback? = null
    private var hasUnFinishOrder: Boolean = false
    private val defaultTimeFormat = "yyyy/MM/dd"

    inner class TaskHolder(private val viewBinding: ItemTaskBinding) :
        RecyclerView.ViewHolder(viewBinding.root) {

        @SuppressLint("SetTextI18n")
        fun bind(taskVo: TaskVo, position: Int) {
            viewBinding.tvTaskProject.text = NameMappingUtils.getProjectName(taskVo.proj) ?: "--"
            viewBinding.tvTaskType.text = NameMappingUtils.getTaskName(taskVo.task) ?: "--"
            viewBinding.tvTaskPlatform.text = NameMappingUtils.getPlatformName(taskVo.app) ?: "--"
            viewBinding.tvTaskNumber.text = "剩余量：" + taskVo.task_count.toString()
//            2021-03-03 00:00:00
            val startTime = formatTime(taskVo.begin_time)
            val endTime = formatTime(taskVo.end_time)
            viewBinding.tvTaskDate.text = "$startTime-$endTime"
            viewBinding.tvReceive.singleClick {
                callback?.onReceiveTask(taskVo)
            }
            viewBinding.tvReceive.isEnabled = !hasUnFinishOrder
        }

        private fun formatTime(time: String?): String {
            return time?.let {
                try {
                    string2Millis(it, "yyyy-MM-dd HH:mm:ss").millis2String(defaultTimeFormat)
                } catch (e: Exception) {
                    "--"
                }
            } ?: "--"
        }
    }


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TaskHolder {
        return TaskHolder(
            ItemTaskBinding.inflate(
                LayoutInflater.from(parent.context),
                parent,
                false
            )
        )
    }

    override fun onBindViewHolder(holder: TaskHolder, position: Int) {
        holder.bind(data[position], position)
    }

    override fun getItemCount(): Int {
        return data.size
    }

    interface Callback {
        fun onReceiveTask(taskVo: TaskVo)
    }

    fun setEnableReceiveTask(hasUnFinishOrder: Boolean) {
        this.hasUnFinishOrder = hasUnFinishOrder
    }
}